package com.example.e_comm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.e_comm.entity.Permission;
import com.example.e_comm.entity.Role;
import com.example.e_comm.entity.RolePermission;
import com.example.e_comm.mapper.RoleMapper;
import com.example.e_comm.mapper.RolePermissionMapper;
import com.example.e_comm.service.PermissionService;
import com.example.e_comm.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;


@Service
@Transactional
public class RoleServiceImpl
        extends ServiceImpl<RoleMapper, Role>
        implements RoleService {
    @Autowired
    private RoleMapper mapper;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    @Override
    public void assignPermissions(Long roleId, List<Long> pIds) {
        //清空角色原有权限关系-- role_permission
        rolePermissionMapper.delete(new QueryWrapper<RolePermission>()
                .eq("role_id", roleId));
        //为角色分配新的权限
        if(pIds != null && !pIds.isEmpty()){
            List<RolePermission> rps = pIds.stream()
                    .map(pId -> {
                RolePermission rp = new RolePermission();
                rp.setRoleId(roleId);
                rp.setPermissionId(pId);
                return rp;
            }).collect(Collectors.toList());
            //批量插入角色权限关系
            for(RolePermission rp : rps){
                rolePermissionMapper.insert(rp);
            }
        }
    }

    @Override
    public void assignPermissions(Long roleId, Long[] pIds) {

    }


    @Override
    public List<Role> getPermissionsByUserId(Long userId) {
        return mapper.getRoleByUserId(userId);
    }

    @Override
    public Role getRoleWithPermissions(Long roleId) {
        //获取角色详情
        Role role = this.getById(roleId);
        //查角色的权限列表
        if(role != null){
            List<Permission> permissions = permissionService.getPermissionsByRoleId(roleId);
            role.setPermissions(permissions);
        }
        return role;
    }
}
